# Script to test multiple tasks with progress tracking
# This will create 20 concurrent tasks and monitor them all

# Number of tasks to create
$numTasks = 20

# Array to store task IDs
$taskIds = @()

Write-Host "Creating $numTasks concurrent tasks..." -ForegroundColor Cyan

# Create multiple tasks
for ($i = 1; $i -le $numTasks; $i++) {
    $number = $i * 100
    Write-Host "Creating task $i with number $number..." -ForegroundColor Yellow
    
    try {
        $response = Invoke-RestMethod -Method Post -Uri "http://localhost:8000/tasks/add" -ContentType "application/json" -Body "{`"number`": $number}"
        $taskIds += $response.task_id
        
        Write-Host "  Created task with ID: $($response.task_id)" -ForegroundColor Green
    } catch {
        Write-Host "  Error creating task: $_" -ForegroundColor Red
    }
}

Write-Host "`nAll $numTasks tasks created. Monitoring status...`n" -ForegroundColor Cyan

# Function to check task status
function Get-TaskStatus {
    param (
        [string]$taskId
    )
    
    try {
        $status = Invoke-RestMethod -Method Get -Uri "http://localhost:8000/tasks/$taskId"
        return $status
    } catch {
        return $null
    }
}

# Monitor all tasks until complete
$allComplete = $false
$iteration = 1
$taskStatuses = @{}

# Initialize task tracking
foreach ($taskId in $taskIds) {
    $taskStatuses[$taskId] = @{
        Status = "PENDING"
        Progress = 0
        InputNumber = 0
        Result = $null
        StartTime = $null
        EndTime = $null
    }
}

$startTime = Get-Date

while (-not $allComplete) {
    $allComplete = $true
    
    # Clear screen for cleaner display
    Clear-Host
    
    $currentTime = Get-Date
    $elapsedTime = $currentTime - $startTime
    
    Write-Host "Status Check Iteration $iteration | Elapsed: $($elapsedTime.ToString('hh\:mm\:ss'))`n" -ForegroundColor Cyan
    
    # Counter for completed tasks
    $completedCount = 0
    $pendingCount = 0
    $processingCount = 0
    
    # Check status of each task
    foreach ($taskId in $taskIds) {
        $status = Get-TaskStatus -taskId $taskId
        
        if ($null -eq $status) {
            Write-Host "Task $($taskId.Substring(0, 8))... - Error retrieving status" -ForegroundColor Red
            continue
        }
        
        $statusText = $status.status
        $progress = $status.progress
        $inputNumber = $status.input_data.number
        
        # Update task tracking
        $taskStatuses[$taskId].Status = $statusText
        $taskStatuses[$taskId].Progress = $progress
        $taskStatuses[$taskId].InputNumber = $inputNumber
        
        if ($statusText -eq "PROCESSING" -and $taskStatuses[$taskId].StartTime -eq $null) {
            $taskStatuses[$taskId].StartTime = Get-Date
        }
        
        if (($statusText -eq "DONE" -or $statusText -eq "SUCCESS" -or $statusText -eq "FAILED") -and $taskStatuses[$taskId].EndTime -eq $null) {
            $taskStatuses[$taskId].EndTime = Get-Date
            if ($status.result -and $status.result.result) {
                $taskStatuses[$taskId].Result = $status.result.result
            }
        }
        
        # Update counters
        if ($statusText -eq "DONE" -or $statusText -eq "SUCCESS") {
            $completedCount++
        } elseif ($statusText -eq "PROCESSING" -or $statusText -eq "PROGRESS" -or $statusText -eq "STARTED") {
            $processingCount++
        } elseif ($statusText -eq "PENDING") {
            $pendingCount++
        }
        
        # If any task is not done, we're not complete
        if ($statusText -ne "DONE" -and $statusText -ne "SUCCESS" -and $statusText -ne "FAILED" -and $statusText -ne "FAILURE") {
            $allComplete = $false
        }
    }
    
    # Display summary
    Write-Host "Summary: $completedCount completed, $processingCount processing, $pendingCount pending`n" -ForegroundColor White
    
    # Display active tasks (processing tasks)
    Write-Host "Active Tasks:" -ForegroundColor Yellow
    $displayCount = 0
    
    foreach ($taskId in $taskIds) {
        $taskStatus = $taskStatuses[$taskId]
        
        if ($taskStatus.Status -eq "PROCESSING" -or $taskStatus.Status -eq "PROGRESS" -or $taskStatus.Status -eq "STARTED") {
            $displayCount++
            
            # Create a progress bar
            $progressBar = "["
            $barWidth = 30
            $filledWidth = [Math]::Floor($barWidth * ($taskStatus.Progress / 100))
            
            for ($i = 0; $i -lt $barWidth; $i++) {
                if ($i -lt $filledWidth) {
                    $progressBar += "="
                } else {
                    $progressBar += " "
                }
            }
            
            $progressBar += "] $($taskStatus.Progress)%"
            
            # Display task info
            $shortId = $taskId.Substring(0, 8) + "..."
            $processingTime = ""
            if ($taskStatus.StartTime -ne $null) {
                $processingTime = " | Time: " + ($currentTime - $taskStatus.StartTime).ToString('mm\:ss')
            }
            
            Write-Host "[$shortId] Input: $($taskStatus.InputNumber) | $progressBar$processingTime" -ForegroundColor Cyan
        }
    }
    
    if ($displayCount -eq 0) {
        Write-Host "  No active tasks" -ForegroundColor DarkGray
    }
    
    # If we're not done, wait before next check
    if (-not $allComplete) {
        Write-Host "`nWaiting before next check..." -ForegroundColor DarkGray
        Start-Sleep -Seconds 1
        $iteration++
    }
}

# Final results
Clear-Host
Write-Host "All tasks completed!" -ForegroundColor Green
$totalTime = (Get-Date) - $startTime
Write-Host "Total execution time: $($totalTime.ToString('hh\:mm\:ss'))`n" -ForegroundColor Cyan

# Display summary table
Write-Host "Results Summary:`n" -ForegroundColor Yellow

# Sort tasks by completion time
$sortedTasks = $taskIds | Sort-Object { 
    if ($taskStatuses[$_].EndTime -ne $null -and $taskStatuses[$_].StartTime -ne $null) {
        ($taskStatuses[$_].EndTime - $taskStatuses[$_].StartTime).TotalSeconds
    } else {
        999999  # Large number for tasks without timing
    }
}

# Table header
Write-Host "Task ID                               | Input | Result   | Status   | Processing Time" -ForegroundColor White
Write-Host "----------------------------------------------------------------------" -ForegroundColor White

foreach ($taskId in $sortedTasks) {
    $taskStatus = $taskStatuses[$taskId]
    $shortId = $taskId.Substring(0, 8) + "..."
    
    $processingTime = "N/A"
    if ($taskStatus.StartTime -ne $null -and $taskStatus.EndTime -ne $null) {
        $processingTime = ($taskStatus.EndTime - $taskStatus.StartTime).ToString('mm\:ss\.fff')
    }
    
    $resultText = if ($taskStatus.Result -ne $null) { $taskStatus.Result } else { "N/A" }
    
    # Color based on status
    $color = switch ($taskStatus.Status) {
        "DONE" { "Green" }
        "SUCCESS" { "Green" }
        "FAILED" { "Red" }
        "FAILURE" { "Red" }
        default { "White" }
    }
    
    Write-Host "$shortId | $($taskStatus.InputNumber.ToString().PadLeft(5)) | $($resultText.ToString().PadLeft(8)) | $($taskStatus.Status.PadRight(8)) | $processingTime" -ForegroundColor $color
}

# Analysis
Write-Host "`nAnalysis:" -ForegroundColor Yellow

# Calculate average processing time
$processingTimes = @()
foreach ($taskId in $taskIds) {
    if ($taskStatuses[$taskId].StartTime -ne $null -and $taskStatuses[$taskId].EndTime -ne $null) {
        $processingTimes += ($taskStatuses[$taskId].EndTime - $taskStatuses[$taskId].StartTime).TotalSeconds
    }
}

if ($processingTimes.Count -gt 0) {
    $avgProcessingTime = ($processingTimes | Measure-Object -Average).Average
    $minProcessingTime = ($processingTimes | Measure-Object -Minimum).Minimum
    $maxProcessingTime = ($processingTimes | Measure-Object -Maximum).Maximum
    
    Write-Host "Average processing time: $($avgProcessingTime.ToString('F2')) seconds" -ForegroundColor Cyan
    Write-Host "Minimum processing time: $($minProcessingTime.ToString('F2')) seconds" -ForegroundColor Cyan
    Write-Host "Maximum processing time: $($maxProcessingTime.ToString('F2')) seconds" -ForegroundColor Cyan
    Write-Host "Total tasks completed: $completedCount" -ForegroundColor Cyan
    
    # Calculate tasks per second
    $tps = $completedCount / $totalTime.TotalSeconds
    Write-Host "Average throughput: $($tps.ToString('F2')) tasks per second" -ForegroundColor Cyan
}